from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 


class operationComp(OWRpy):
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # python variables
        self.data = {}
        self.RFunctionParam_X = ''
        self.ncol = 0

        # Unique R variable
        self.setRvariableNames(['perturbationVector'])
        self.setRvariableNames(['powerAlpha'])
        self.setRvariableNames(['operatedComp'])
        
        # Inputs
        self.inputs.addInput('Data Table', 'Data Table', signals.base.RMatrix, self.processX)
        
        # Outputs
        self.outputs.addOutput('Data Table', 'Data Table', signals.base.RMatrix) # trace problem with outputs

        #GUI.
        area = widgetBox(self.controlArea,orientation='vertical')  

        self.operation = redRGUI.base.radioButtons(area,  label = "Operation", 
        buttons = [('+','Perturbation (+)'),
        ('-','Perturbation (-)'),
        ('*','Powering (.)')],
        setChecked='+', orientation='vertical', callback = self.onOpChange)

        self.infoBox = redRGUI.base.groupBox(area, label='Vector')
        self.simplexNames = redRGUI.base.lineEdit(self.infoBox, label = 'Simplex elements:', text = '')
        self.simplexNames.setDisabled(True)
        
        self.vectorPert = redRGUI.base.lineEdit(self.infoBox, label = 'Perturbation vector (comma separated):', text = '')
        self.alphaPow = redRGUI.base.lineEdit(self.infoBox, label = 'Powering value:', text = '')
        self.alphaPow.setDisabled(True)
        
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignRight, 
        callback = self.commitFunction, processOnInput=True)
    
    def onOpChange(self):
        self.vectorPert.setDisabled(True)
        self.alphaPow.setDisabled(True)
        if self.operation.getCheckedId() == '+' or self.operation.getCheckedId() == '-' :
            self.vectorPert.setEnabled(True)
        elif self.operation.getCheckedId() == '*' :
            self.alphaPow.setEnabled(True)

    def processX(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_X=data.getData()
            self.data = data
            self.simplexNames.setText(str(self.R('colnames('+self.RFunctionParam_X+')')))
            self.commitFunction()
        else:
            self.RFunctionParam_X=''
            
    def commitFunction(self):
        if str(self.RFunctionParam_X) == '':
            self.status.setText('Data is missing.')
            return

        if self.operation.getCheckedId() == '+' or self.operation.getCheckedId() == '-' :
            if str(self.vectorPert.text()) == '':
                self.status.setText('Error: a vector should be entered in the "Perturbation vector" field.')
                return
            else:
                self.R(self.Rvariables['perturbationVector']+'<-c('+self.vectorPert.text()+')')
                self.ncolX = self.R('ncol('+self.RFunctionParam_X+')')
                self.lenV = self.R('length('+self.Rvariables['perturbationVector']+')')
                if self.ncolX != self.lenV:
                    self.status.setText('Error: simplex has '+unicode(self.ncolX)+' columns, while the vector has '+unicode(self.lenV)+' elements.')
                    return
                else:
                    self.status.setText('The vector is valid.')
        
                self.R(self.Rvariables['operatedComp']+'<-'+self.RFunctionParam_X+self.operation.getCheckedId()+self.Rvariables['perturbationVector'], processingNotice=True)
        
        elif self.operation.getCheckedId() == '*' :
            if str(self.vectorPert.text()) == '':
                self.status.setText('Error: a single should be entered in the "Perturbation vector" field.')
                return
            else:
                self.R(self.Rvariables['powerAlpha']+'<-'+self.alphaPow.text())
                self.R(self.Rvariables['operatedComp']+'<-'+self.RFunctionParam_X+self.operation.getCheckedId()+self.Rvariables['powerAlpha'], processingNotice=True)
        
        
        newData = signals.base.RMatrix(self, data = self.Rvariables['operatedComp'], checkVal = False) 
        self.rSend('Data Table', newData)
            